package com.laboratory.Process;

import com.laboratory.thread.TaskEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * Created by 30868 on 2019/04/10.
 */
public class CallableTest3 {

    public static void main(String[] args) {

        // 新建 10 个线程，每个线程分别负责累加 1~10, 11~20, ..., 91~100
        long startTime = System.currentTimeMillis();
        List<Future<Integer>> futureTasks = new ArrayList<>();
        int total = 0;
        for (int i = 0; i < 10; i++) {
            final int begin = i * 10 + 1;
            final int end = (i + 1) * 10;
            Future future = TaskEngine.getInstance().submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    long startTime = System.currentTimeMillis();
                    int result = 0;
                    for (int j =begin; j<= end; j++){
                        result += j;
                    }
                    if(begin ==1) {
                    Thread.sleep(200);
                        Thread.interrupted();
                        int a = 1/0;
                    }
                    System.out.printf("(%s) - 运行结束，结果为 %d, 运行时间为 %s\n", Thread.currentThread().getName(), result,
                            System.currentTimeMillis() - startTime);
                    return result;
                }
            });
            futureTasks.add(future);

        }
        for (Future<Integer> futureTask : futureTasks) {
            try {
                total += futureTask.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        System.out.printf("(%s) - 运行结束，结果为 %d, 运行时间为 %s\n", Thread.currentThread().getName(), total,
                System.currentTimeMillis() - startTime);

    }

}
